"""
邮件系统初始化脚本
创建默认邮件模板和配置
"""

import json
from sqlalchemy.orm import Session
from datetime import datetime

from app.core.database import SessionLocal
from app.core.email_config import validate_email_config
from app.core.logging import get_logger
from app.models.email_message import EmailTemplate, EmailType

logger = get_logger(__name__)


def create_default_templates(db: Session):
    """创建默认邮件模板"""
    
    default_templates = [
        {
            "name": "welcome",
            "display_name": "欢迎邮件",
            "description": "新用户注册欢迎邮件",
            "subject_template": "欢迎加入 {{ platform_name }}！",
            "body_template": "welcome.html",
            "email_type": EmailType.WELCOME,
            "is_system": True,
            "variables": {
                "user_name": "用户姓名",
                "user_email": "用户邮箱",
                "user_id": "用户ID",
                "platform_name": "平台名称",
                "platform_url": "平台URL",
                "registration_date": "注册日期",
                "help_url": "帮助中心URL"
            }
        },
        {
            "name": "user_message",
            "display_name": "用户消息",
            "description": "用户间发送消息的邮件模板",
            "subject_template": "{{ subject }} - 来自 {{ sender_name }}",
            "body_template": "user_message.html",
            "email_type": EmailType.USER_MESSAGE,
            "is_system": True,
            "variables": {
                "sender_name": "发送者姓名",
                "sender_email": "发送者邮箱",
                "recipient_name": "接收者姓名",
                "subject": "消息主题",
                "message": "消息内容",
                "platform_name": "平台名称",
                "platform_url": "平台URL",
                "sent_time": "发送时间",
                "help_url": "帮助中心URL"
            }
        },
        {
            "name": "notification",
            "display_name": "系统通知",
            "description": "系统通知邮件模板",
            "subject_template": "{{ notification_title }} - {{ platform_name }}",
            "body_template": "notification.html",
            "email_type": EmailType.NOTIFICATION,
            "is_system": True,
            "variables": {
                "user_name": "用户姓名",
                "notification_title": "通知标题",
                "notification_message": "通知内容",
                "notification_type": "通知类型(info/success/warning/error)",
                "notification_time": "通知时间",
                "platform_name": "平台名称",
                "platform_url": "平台URL",
                "action_url": "操作链接",
                "action_text": "操作按钮文本",
                "details": "详细信息字典",
                "additional_info": "附加信息列表",
                "help_url": "帮助中心URL"
            }
        },
        {
            "name": "password_reset",
            "display_name": "密码重置",
            "description": "密码重置邮件模板",
            "subject_template": "密码重置请求 - {{ platform_name }}",
            "body_template": "password_reset.html",
            "email_type": EmailType.PASSWORD_RESET,
            "is_system": True,
            "variables": {
                "user_name": "用户姓名",
                "user_email": "用户邮箱",
                "reset_code": "重置验证码",
                "reset_url": "重置链接",
                "request_time": "请求时间",
                "request_ip": "请求IP",
                "user_agent": "用户代理",
                "expiry_hours": "过期小时数",
                "platform_name": "平台名称",
                "help_url": "帮助中心URL"
            }
        },
        {
            "name": "verification",
            "display_name": "邮箱验证",
            "description": "邮箱验证邮件模板",
            "subject_template": "邮箱验证 - {{ platform_name }}",
            "body_template": "verification.html",
            "email_type": EmailType.VERIFICATION,
            "is_system": True,
            "variables": {
                "user_name": "用户姓名",
                "user_email": "用户邮箱",
                "verification_code": "验证码",
                "verification_url": "验证链接",
                "expiry_minutes": "过期分钟数",
                "platform_name": "平台名称",
                "help_url": "帮助中心URL"
            }
        }
    ]
    
    created_count = 0
    
    for template_data in default_templates:
        # 检查模板是否已存在
        existing = db.query(EmailTemplate).filter(
            EmailTemplate.name == template_data["name"]
        ).first()
        
        if existing:
            logger.info(f"邮件模板已存在: {template_data['name']}")
            continue
        
        # 创建新模板
        template = EmailTemplate(
            name=template_data["name"],
            display_name=template_data["display_name"],
            description=template_data["description"],
            subject_template=template_data["subject_template"],
            body_template=template_data["body_template"],
            email_type=template_data["email_type"],
            is_system=template_data["is_system"],
            variables=json.dumps(template_data["variables"], ensure_ascii=False)
        )
        
        db.add(template)
        created_count += 1
        logger.info(f"创建邮件模板: {template_data['name']}")
    
    if created_count > 0:
        db.commit()
        logger.info(f"✅ 成功创建 {created_count} 个邮件模板")
    else:
        logger.info("📧 所有默认邮件模板已存在")


def init_email_system():
    """初始化邮件系统"""
    try:
        logger.info("🚀 开始初始化邮件系统...")
        
        # 验证邮件配置
        if not validate_email_config():
            logger.error("❌ 邮件配置验证失败，跳过邮件系统初始化")
            return False
        
        # 创建数据库会话
        db = SessionLocal()
        
        try:
            # 创建默认模板
            create_default_templates(db)
            
            logger.info("✅ 邮件系统初始化完成")
            return True
            
        except Exception as e:
            logger.error(f"❌ 邮件系统初始化失败: {e}")
            db.rollback()
            return False
        finally:
            db.close()
            
    except Exception as e:
        logger.error(f"❌ 邮件系统初始化异常: {e}")
        return False


def test_email_connection():
    """测试邮件连接"""
    try:
        from app.core.email_config import fast_mail
        from fastapi_mail import MessageSchema, MessageType
        
        # 创建测试邮件
        message = MessageSchema(
            subject="FastAPI Platform 邮件系统测试",
            recipients=["18967498922@163.com"],  # 发送给自己进行测试
            body="""
            <h2>邮件系统测试</h2>
            <p>这是一封测试邮件，用于验证 FastAPI Platform 邮件系统是否正常工作。</p>
            <p>如果您收到这封邮件，说明邮件系统配置成功！</p>
            <p>发送时间: {}</p>
            """.format(datetime.now().strftime("%Y-%m-%d %H:%M:%S")),
            subtype=MessageType.html
        )
        
        # 发送测试邮件
        import asyncio
        asyncio.run(fast_mail.send_message(message))
        
        logger.info("✅ 邮件连接测试成功")
        return True
        
    except Exception as e:
        logger.error(f"❌ 邮件连接测试失败: {e}")
        return False


if __name__ == "__main__":
    # 初始化邮件系统
    success = init_email_system()
    
    if success:
        # 测试邮件连接
        test_email_connection()
    else:
        logger.error("邮件系统初始化失败，跳过连接测试")